package com.cxs.controller;

import com.cxs.model.Scheduled;
import com.cxs.service.ScheduledService;
import com.cxs.service.ScheduledTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Project: scheduled-demo
 * @Author: cxs2014501@163.com
 * @Create: 2023/1/16 15:48
 * @Description:
 **/
@RestController
@RequestMapping("task")
public class TaskController {

    @Autowired
    private ScheduledTaskService scheduledTaskService;

    @Autowired
    private ScheduledService scheduledService;


    @GetMapping("start")
    public String start(@RequestParam("id") Integer id){
        Scheduled scheduled = scheduledService.getById(id);
        if (scheduled == null) {
            return "任务不存在";
        }
        if (scheduledTaskService.isStart(scheduled.getScheduledKey())) {
            return "任务已运行,请勿重复启动";
        } else {
            if (scheduledTaskService.start(scheduled.getScheduledKey(), scheduled)) {
                Scheduled s = new Scheduled();
                s.setId(scheduled.getId());
                s.setStatus(1);
                if (scheduledService.updateById(s)) {
                    return "任务启动成功";
                }
            }
        }
        return "任务启动失败";
    }

    @GetMapping("stop")
    public String stop(@RequestParam("id") Integer id){
        Scheduled scheduled = scheduledService.getById(id);
        if (scheduled == null) {
            return "任务不存在";
        }
        if (!scheduledTaskService.isStart(scheduled.getScheduledKey())) {
            return "任务已停止,请勿重复停止";
        } else {
            if (scheduledTaskService.stop(scheduled.getScheduledKey())) {
                Scheduled s = new Scheduled();
                s.setId(scheduled.getId());
                s.setStatus(2);
                if (scheduledService.updateById(s)) {
                    return "任务停止成功";
                }
            }
        }
        return "任务停止失败";
    }
}
